<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-06-21 16:36:53
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-08-06 15:02:14
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\EquipManage\EquipType\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, watch, reactive, h } from 'vue'
import { ElTree, ElInput, ElTag, ElMessage } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import EquipTypeApi from '@/api/equip/equipType'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useDictStore } from '@/store/modules/dictData'
import { useEquipStore } from '@/store/modules/equip'
import { useDeptStore } from '@/store/modules/dept'
import { FacilityTypeList } from '@/api/equip/type'
import { BaseButton } from '@/components/Button'
import TemplateVue from './components/Template.vue'
import EditType from './components/EditTypeTree.vue'
import EditCofig from './components/EditCofig.vue'
import DeptApi from '@/api/dept'
import { Dialog } from '@/components/Dialog'
const { t } = useI18n()
const ids = ref<number[]>([])
const EquipStore = useEquipStore()
const DeptStore = useDeptStore()
const treeEl = ref<typeof ElTree>() //树结构
const currentNodeKey = ref<number>() //树结构ID
const departmentList = ref<any>([]) //树结构数据
const Title = ref<string | undefined>('') //表格名称
const DictStore = useDictStore()
//获取字典
DictStore.setDict('model_form_type') //表单类型
DictStore.setDict('maint_freq') //维护频率
if (DeptStore.DeptListTypeDetail.length == 0) {
  DeptStore.setFacilityTypeDetail()
}
//表格内容接口
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const i = await EquipTypeApi.GetFacTypeConfigList({
      faciId: unref(currentNodeKey),
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize)
    })
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = await EquipTypeApi.DeletFacTypeConfig(unref(ids)[0])
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const FormDisabled = ref(true)
//表格结构
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    fixed: 'left',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'faciId',
    label: t('组织类型'),
    width: 200,
    table: {
      hidden: true
    },
    form: {
      component: 'TreeSelect',
      colProps: {
        span: 20
      },
      componentProps: {
        renderAfterExpand: false,
        showCheckbox: true,
        checkStrictly: true,
        checkOnClickNode: true,
        data: departmentList,
        nodeKey: 'id',
        props: {
          label: 'label'
        }
      }
    }
  },
  {
    field: 'status',
    label: t('状态'),
    formatter: (_: Recordable, __: any, cellValue: number) => {
      return h(
        ElTag,
        {
          type: cellValue == 0 ? 'primary' : 'danger'
        },
        () => (cellValue == 0 ? t('正常') : t('停用'))
      )
    },
    search: {
      hidden: true
    },
    form: {
      component: 'RadioGroup',
      colProps: {
        span: 20
      },
      componentProps: {
        options: [
          {
            label: '正常',
            value: '0'
          },
          {
            label: '停用',
            value: '1'
          }
        ]
      }
    }
  },
  {
    field: 'formType',
    label: t('表单类型'),
    width: 200,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.model_form_type?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel)
        }
      })
    },
    form: {
      component: 'RadioGroup',
      colProps: {
        span: 20
      },
      componentProps: {
        options: DictStore.$state.model_form_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'formNo',
    label: t('表单编号'),
    width: 150,
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'formName',
    label: t('表单名'),
    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'deptId',
    label: t('使用于'),
    width: 200,
    formatter: (_: Recordable, __: any, cellValue: number) => {
      if (cellValue !== undefined && cellValue) {
        return DeptStore.getDeptName(cellValue)[0]?.deptName
      }
    },
    form: {
      colProps: {
        span: 20
      },
      component: 'TreeSelect',
      componentProps: {
        renderAfterExpand: false,
        showCheckbox: true,
        checkStrictly: true,
        checkOnClickNode: true,
        nodeKey: 'id',
        props: {
          label: 'label'
        }
      },
      optionApi: async () => {
        const res = await DeptApi.GetDeptListTree()
        return res.data
      }
    }
  },
  {
    field: 'maintFreq',
    label: t('维护频率'),
    width: 150,
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.maint_freq?.map((item) => {
        if (item.dictValue == cellValue) {
          return t(item.dictLabel)
        }
      })
    },
    form: {
      component: 'Select',
      colProps: {
        span: 20
      },
      componentProps: {
        options: DictStore.$state.maint_freq?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 200,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'Edit')}>
                {t('修改')}
              </span>
              <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
                {t('查看')}
              </span>
              <span class="TableBtn" onClick={() => TemplateAction(data.row, 'Template')}>
                {t('模板')}
              </span>
              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const fetchDepartment = async () => {
  await EquipStore.setFacilityTypeTree()
  departmentList.value = EquipStore.getFacilityTypeTree
  currentNodeKey.value = EquipStore.getFacilityTypeTree[0]?.id || null //树结构ID也为第一个
  unref(treeEl)?.setCurrentKey(currentNodeKey.value) //应用到树结构
}
fetchDepartment() //获取树结构
const currentDepartment = ref('') //树结构搜索框内容
watch(
  () => currentDepartment.value, //监控树结构搜索框内容变化
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: any) => {
  //树结构点击
  currentNodeKey.value = data.id
  Title.value = data.label
  currentPage.value = 1 //页面为第一页
  getList() //表格更新
}
const filterNode = (value: string, data: any) => {
  //树结构变化
  if (!value) return true
  return data.label.includes(value)
}
const currentRow = ref<FacilityTypeList>()
const saveLoading = ref(false)
const delLoading = ref(false)
//表格删除操作
const delData = async (row: FacilityTypeList | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: any) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const dialogVisible = ref(false)
const TemplateVisible = ref(false)
const dialogTitle = ref('')
const EditCofigRef = ref()
const EditTypeRef = ref()
const SureCompont = ref('') //确认打开弹窗为类型修改还是配置表单
const actionType = ref('')
const facilityType = ref('')
const SubmitConfig = async () => {
  const write = unref(EditCofigRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await EquipTypeApi.AddFacTypeConfig(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else if (actionType.value == 'Edit') {
      //修改字
      res.value = await EquipTypeApi.EditFacTypeConfig(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
const SubmitType = async () => {
  const write = unref(EditTypeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (facilityType.value == 'add') {
      res.value = await EquipTypeApi.AddFacilityType(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      //修改字
      res.value = await EquipTypeApi.EditFacilityType(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      fetchDepartment() //获取树结构
      currentPage.value = 1
      getList()
    }
  }
}
const TemplateRef = ref()
const save = async () => {
  if (SureCompont.value == 'Config') {
    SubmitConfig()
  } else if (SureCompont.value == 'Type') {
    SubmitType()
  } else {
    const write = unref(TemplateRef)
    const formData = await write?.AssembleFormData()
    const i = await EquipTypeApi.FacTypeConfig(formData)
    if (i) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error('保存失败')
    }
    TemplateVisible.value = false
  }
}
//表格中操作
const action = (row: FacilityTypeList, type: string) => {
  SureCompont.value = 'Config'
  actionType.value = type
  dialogVisible.value = true //打开弹窗
  if (type == 'add') {
    dialogTitle.value = '新增'
    FormDisabled.value = false
    currentRow.value = {}
  } else if (type == 'Edit') {
    dialogTitle.value = '修改'
    FormDisabled.value = false
    currentRow.value = row
  } else {
    dialogTitle.value = '查看'
    FormDisabled.value = true
    currentRow.value = row
  }
}
const TemplateAction = (row: FacilityTypeList, type: string) => {
  actionType.value = type
  TemplateVisible.value = true //打开弹窗
  currentRow.value = row
  EquipStore.setFacilityById(row.id)
}

//类型中操作
const EditTypeTree = async (type: string) => {
  SureCompont.value = 'Type'
  if (type == 'delete') {
    const res = await EquipTypeApi.DeletFacilityType(currentNodeKey.value)
    if (res) {
      fetchDepartment() //获取树结构
      currentPage.value = 1 //页面为第一页
      getList() //表格更新
    }
  } else if (type == 'edit') {
    EquipStore.setFacilityTypeDetail(currentNodeKey.value)
    dialogVisible.value = true //打开弹窗
    facilityType.value = type
  } else {
    EquipStore.FacilityTypeDetail = { parentId: currentNodeKey.value }
    dialogVisible.value = true //打开弹窗
    facilityType.value = type
  }
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px min-h-[580px]" title="类型管理">
      <div class="flex justify-around mb-[10px]">
        <BaseButton type="primary" size="small" @click="EditTypeTree('add')">新增</BaseButton>
        <BaseButton type="primary" size="small" @click="EditTypeTree('edit')">修改</BaseButton>
        <BaseButton type="danger" size="small" @click="EditTypeTree('delete')">删除</BaseButton>
      </div>
      <ElInput
        v-model="currentDepartment"
        class="flex-[2] mb-[10px]"
        :placeholder="t('组织名称')"
        clearable
      />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'departmentName'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.label" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.label }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px" :title="Title">
      <!-- <div class="flex"> -->
      <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="13" />新增
      </BaseButton>
      <!-- </div> -->
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <Dialog v-model="dialogVisible" :title="dialogTitle" style="width: 500px" maxHeight="400px">
      <EditCofig
        ref="EditCofigRef"
        v-if="SureCompont == 'Config'"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :FormDisabled="FormDisabled"
      />
      <EditType
        ref="EditTypeRef"
        v-if="SureCompont == 'Type'"
        :current-row="EquipStore.getFacilityTypeDetail"
      />
      <template #footer v-if="actionType !== 'Detail'">
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
    <Dialog v-model="TemplateVisible" title="自定义模板" style="width: 1200px" maxHeight="500px">
      <TemplateVue ref="TemplateRef" :current-row="currentRow" />
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="TemplateVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style scoped>
/* .el-tree {
  height: 410px;
  overflow: hidden;
  overflow-y: scroll;
} */
.el-tree-node:focus > .el-tree-node__content {
  color: #409eff;
}
.el-card__body {
  padding: 10px;
  /* height: 90%; */
}
.CloseBtn {
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
.el-collapse-item {
  padding: 15px 0;
}
.el-collapse-item__content {
  padding-bottom: 0;
}
.el-collapse-item__header {
  width: 62px;
  height: 24px;
  border-radius: 2px;
  color: white;
  background: #409eff;
  justify-content: center;
  font-size: 12px;
}
.el-collapse-item__arrow {
  margin: 0 2px;
}

:deep(.TableBtn) {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
